<template>
    <div class='fxn-body fxn-detail'>
        <el-page-header @back="handleBack">
            <template #content>
            <span class="text-large font-600 mr-3"> 案件列表 </span>
            </template>
        </el-page-header>
        <!-- Back Header End -->
        <div class="fxn-detail-user fxn-margin-t-20">
            <div class="title">
                <span class="icon">{{formatType($filter.caseType(detailData.case_type))}}</span>
                {{detailData.title}} 
                (案件ID：{{detailData.id}})
            </div>
            <div class="status">
                <div class="item" v-if="detailData.key_name">关联客户：<span><el-link type="danger" @click="handlePath">{{detailData.key_name}}</el-link></span></div>
                <div class="item">案件类型：<span>{{$filter.caseType(detailData.case_type)}}</span></div>
                <div class="item">案由：<span>{{$filter.businessType(detailData.business_type)}}</span></div>
                <div class="item">更新时间：<span>{{$filter.dateTime(detailData.update_time,1)}}</span></div>
            </div>
            <div class="button">
                <el-button v-if="authMenu('sys_case_detail_editcase')" type="primary" plain icon="EditPen" @click="handleAddEdit">编辑案件</el-button>
                <el-button v-if="authMenu('sys_case_detail_note')" type="primary" plain icon="EditPen" @click="handleFollow">添加跟进</el-button>
                <el-button v-if="authMenu('sys_case_detail_court_add')" type="primary" plain icon="School" @click="handleSession">添加开庭</el-button>
                <el-button v-if="authMenu('sys_case_detail_judgments_add')" type="primary" plain icon="Coordinate" @click="handleJudgment">添加判决</el-button>
                <el-button v-if="authMenu('sys_case_detail_preservation_add')" type="primary" plain icon="TrophyBase" @click="handleAddPre">添加保全</el-button>
                <el-button v-if="authMenu('sys_case_detail_close')" type="primary" plain icon="Finished" @click="handleAddFinish(1)">结案</el-button>
                <el-button v-if="authMenu('sys_case_detail_finish')" type="primary" plain icon="Files" @click="handleAddFinish(2)">归档</el-button>
                <el-button v-if="authMenu('sys_case_detail_customer_bind')" type="primary" plain icon="Files" @click="handleOpBind(1,detailData)">{{detailData.key_id != 0 ? '更换客户' : '关联客户'}}</el-button>
                <el-button v-if="authMenu('sys_case_detail_customer_cancel') && detailData.key_id != 0" type="primary" plain icon="Files" @click="handleOpBind(2)">取消关联</el-button>
            </div>
        </div>
        <!-- User End -->
        <div class="fxn-detail-wrap">
            <div class="fxn-tabs">
                <el-tabs v-model="activeName" @tab-change="handleTab">
                    <el-tab-pane v-for="(item,index) in TabData" :key="index" :label="item.label" :name="item.value"></el-tab-pane>
                </el-tabs>
            </div>
            <!-- Tabs End -->
            <BasicInfo v-if="activeName == 1" :detailData="detailData" :closesData="closesData"></BasicInfo>
            <FollowRecord v-if="activeName == 2"></FollowRecord>
            <CourtSession v-if="activeName == 3"></CourtSession>
            <Judgment v-if="activeName == 4"></Judgment>
            <Preservation v-if="activeName == 5"></Preservation>
            <Finance v-if="activeName == 6"></Finance>
            <FileSummary v-if="activeName == 7"></FileSummary>
        </div>
        <!-- Wrap End -->

        <!-- 修改案件 -->
        <dialogForm ref="dialogEdit" :formData="editData" @handleDialog="handleEdit"></dialogForm>
        <!-- 修改案件 End -->

        <!-- 添加跟进 -->
        <noteForm v-model:opDialog="opDialog" :staticData="staticData" :lawcase_status="lawcase_status" @handleSubmit="handleSubmit"></noteForm>
        <!-- 添加跟进 End -->

        <!-- 开庭信息 -->
        <courtForm v-model:opDialog="courtDialog" :staticData="courtData" @handleSubmit="handleSubmit"></courtForm>
        <!-- 开庭信息 End -->

        <!-- 添加判决 -->
        <judgmentForm v-model:opDialog="judgmentDialog" :staticData="judgmentData" :lawcase_status="lawcase_status" @handleSubmit="handleSubmit"></judgmentForm>
        <!-- 添加判决 End -->

        <!-- 保全信息 -->
        <dialogForm ref="dialogPre" :formData="preData" @handleDialog="handlePre"></dialogForm>
        <!-- 保全信息 End -->

        <!-- 结案/归档 -->
        <dialogForm ref="dialogFinish" :formData="finishData" @handleDialog="handleFinish"></dialogForm>
        <!-- 结案/归档 End -->

        <!-- 绑定/更换客户 -->
        <el-dialog v-model="bindDialog" :title="bindTitle" width="800" :before-close="handleBindClose">
            <div class="bind-wrap">
                <div class="fxn-search">
                    <el-form :inline="true" :model="SearchForm" ref="SearchRef">
                        <el-form-item label="客户名称" prop="name">
                            <el-input v-model="SearchForm.name" ></el-input>
                        </el-form-item>
                        <el-form-item label=" ">
                            <el-button icon="Refresh" @click="resetForm('SearchForm')">重置</el-button>
                            <el-button type="primary" icon="Search" @click="getCustomer(1,5)">查询</el-button>
                        </el-form-item>
                    </el-form>
                </div>
                <!-- Section End -->
                <el-table ref="TableRef" border v-loading="loading" :data="customerData" >
                    <el-table-column width="55" align="center">
                        <template #default="scope">
                            <el-radio :label="scope.row.id" v-model="radio" @change.native="handleCurrent(scope.row)">&nbsp;</el-radio>
                        </template>
                    </el-table-column>
                    <el-table-column label="客户名称" prop="name" />
                    <el-table-column label="客户电话" prop="phone" />
                    <el-table-column label="跟进阶段" prop="follow_stage">
                        <template #default="scope">
                            {{$filter.followStage(scope.row.follow_stage)}}
                        </template>
                    </el-table-column>
                </el-table>
                <!-- Table End -->
            </div>
            <div class="bind-page fxn-page">
                <el-pagination v-model:current-page="page" v-model:page-size="perPage" :page-sizes="[10, 50, 100, 200, 500]" layout="total, prev, pager, next" :total="count" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
            <template #footer>
                <el-button @click="handleBindClose">取消</el-button>
                <el-button type="danger" :loading="btnLoading" @click="handleBind">确认</el-button>
            </template>
        </el-dialog>
        <!-- 绑定/更换客户 End -->
    </div>
</template>

<script>
    import dialogForm from '../Common/Form.vue'
    import BasicInfo from './CaseDatail/BasicInfo.vue'
    import FollowRecord from './CaseDatail/FollowRecord.vue'
    import CourtSession from './CaseDatail/CourtSession.vue'
    import Judgment from './CaseDatail/Judgment.vue'
    import Preservation from './CaseDatail/Preservation.vue'
    import Finance from './CaseDatail/Finance.vue'
    import FileSummary from './CaseDatail/FileSummary.vue'
    import noteForm from './Common/noteForm.vue'
    import courtForm from './Common/courtForm.vue'
    import judgmentForm from './Common/judgmentForm.vue'
    import { defineComponent, reactive, getCurrentInstance, onMounted, toRefs, computed } from 'vue'
    import { useRouter } from 'vue-router'
    import { useStore } from 'vuex'
    export default defineComponent({
        components: {dialogForm,BasicInfo,FollowRecord,CourtSession,Judgment,Preservation,Finance,FileSummary,noteForm,courtForm,judgmentForm},
        setup() {
            const { proxy } = getCurrentInstance();
            const router = useRouter();
            const store = useStore();

            //初始化数据
            const state = reactive({
                count: 1,
                page: 1,
                perPage: 5,
                loading: false,
                customerData: [],

                //Tabs
                activeName: 1,
                TabData: [
                    {value: 1, label: '基本资料'},
                    {value: 2, label: '跟进日志'},
                    {value: 3, label: '开庭信息'},
                    {value: 4, label: '判决信息'},
                    {value: 5, label: '保全信息'},
                    {value: 6, label: '财务信息'},
                    {value: 7, label: '文件汇总'},
                ],
                detailData: {},
                closesData: [],

                //编辑案件
                editData: {
                    inline: false,
                    width: '800',
                    title: '编辑案件',
                    labelWidth: '120',
                    data: [
                        {formType: 'input', span: 12, label: '我方当事人', prop: 'name', placeholder: '请输入我方当事人'},
                        {formType: 'input', span: 12, label: '对方当事人', prop: 'priority', placeholder: '请输入对方当事人'},
                        {formType: 'input', span: 12, label: '案件编号', prop: 'case_no', placeholder: '请输入案件编号'},
                        {formType: 'select', span: 12, label: '案由', prop: 'business_type', data: computed(() => store.state.configEnable.business_type), rules: [{ required: true, message: '请选择案由', trigger: 'blur' }], selectlabel: 'value', selectvalue: 'name', placeholder: '请选择'},
                        {formType: 'select', span: 12, label: '业务地区', prop: 'area', data: computed(() => store.state.configEnable.business_area), rules: [{ required: true, message: '请选择业务地区', trigger: 'blur' }], selectlabel: 'value', selectvalue: 'name', placeholder: '请选择'},
                        {formType: 'select', span: 12, label: '委托阶段', prop: 'entrust_stage', data: computed(() => store.state.configEnable.entrust_stage), rules: [{ required: true, message: '请选择委托阶段', trigger: 'blur' }], multiple: true, tags: true, selectlabel: 'value', selectvalue: 'name', placeholder: '请选择'},
                        {formType: 'input', span: 12, label: '诉讼标的额', prop: 'target_amount', placeholder: '请输入诉讼标的额'},
                        {formType: 'input', span: 12, label: '合同金额', prop: 'contract_amount', placeholder: '请输入合同金额'},
                        {formType: 'select', span: 12, label: '承办人', prop: 'lawyer_id', data: computed(() => store.state.userData), rules: [{ required: true, message: '请选择承办人', trigger: 'blur' }], multiple: true, tags: true, selectlabel: 'real_name', selectvalue: 'id', placeholder: '请选择'},
                        {formType: 'input', span: 24, type: 'textarea', rows: 5, label: '移交证据', prop: 'evidence', placeholder: '请输入移交证据'},
                        {formType: 'input', span: 24, type: 'textarea', rows: 5, label: '案件详情', prop: 'description', placeholder: '请输入案件详情'},
                        {formType: 'file', span: 24, label: '上传附件', prop: 'files', size: 200, limit: 100, accept: '.jpg,.png,.docx,.pdf,.xlsx,.pptx,.zip,.rar'},
                    ]
                },

                //操作跟进
                opDialog: false,
                lawcase_status: [],
                staticData: {
                    title: '添加跟进',
                    width: 800,
                    lawcase_id: '',
                    lawcase_status: '',
                },

                //开庭信息
                courtDialog: false,
                courtData: {
                    title: '添加开庭信息',
                    width: 800,
                    lawcase_id: '',
                },

                //添加判决
                judgmentDialog: false,
                judgmentData: {
                    title: '添加判决',
                    width: 800,
                    lawcase_id: '',
                    lawcase_status: '',
                },

                //添加保全
                preData: {
                    inline: false,
                    width: '800',
                    title: '添加保全',
                    labelWidth: '150',
                    data: [
                        {formType: 'datepicker', span: 12, label: '保全期限开始时间', prop: 'security_start_time', type: 'date', format: 'YYYY-MM-DD', rules: [{ required: true, message: '请选择保全期限开始时间', trigger: 'blur' }], placeholder: '请选择'},
                        {formType: 'datepicker', span: 12, label: '保全期限结束时间', prop: 'security_end_time', type: 'date', format: 'YYYY-MM-DD', rules: [{ required: true, message: '请选择保全期限结束时间', trigger: 'blur' }], placeholder: '请选择'},
                        {formType: 'input', span: 12, label: '申请保全金额', prop: 'security_amount', rules: [{ required: true, message: '请输入申请保全金额', trigger: 'blur' },{ pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '请输⼊正确的格式,可保留两位⼩数' }], placeholder: '请输入申请保全金额'},
                        {formType: 'input', span: 12, label: '实际保全金额', prop: 'apply_security_amount', rules: [{ required: true, message: '请输入实际保全金额', trigger: 'blur' },{ pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '请输⼊正确的格式,可保留两位⼩数' }], placeholder: '请输入实际保全金额'},
                        {formType: 'input', span: 12, label: '保全标的物', prop: 'security_thing', rules: [{ required: true, message: '请输入保全标的物', trigger: 'blur' }], placeholder: '请输入保全标的物'},
                        {formType: 'input', span: 24, type: 'textarea', rows: 5, label: '备注', prop: 'remark', placeholder: '请输入备注'},
                    ]
                },

                //结案/归档
                finishData: {
                    inline: false,
                    width: '600',
                    labelWidth: '120',
                },

                //绑定/更换客户
                radio: '',
                bindType: '',
                bindID: '',
                btnLoading: false,
                bindTitle: '绑定客户',
                bindDialog: false,
                SearchRef: '',
                SearchForm: {
                    name: '',
                },
            })

            //获取客户详情
            const getDetail = () => {
                state.loading = true;
                proxy.$http.get('/oa/Lawcase/info',{
                    id: router.currentRoute.value.query.id
                })
                .then(res=> {
                    state.loading = false;
                    const { code, msg ,data } = res;
                    if(code != 1){
                        return proxy.$msg.error(msg);
                    }else{
                        state.detailData = data.info;
                        state.closesData = data.closes;

                        //初始化搜索条件: 案件状态-绑定数据
                        if(state.detailData.case_type == 'type_nonlawsuit'){
                            state.lawcase_status =  computed(() => store.state.configAll.type_nonlawsuit);
                        }
                        if(state.detailData.case_type == 'type_penal'){
                            state.lawcase_status =  computed(() => store.state.configAll.type_penal);
                        }
                        if(state.detailData.case_type == 'type_lawsuit'){
                            state.lawcase_status =  computed(() => store.state.configAll.type_lawsuit);
                        }
                    }
                })
            }

            //打开编辑
            const handleAddEdit = () => {
                proxy.$http.get('/oa/Lawcase/caseForm',{
                    id: router.currentRoute.value.query.id
                })
                .then(res=> {
                    const { code, msg ,data } = res;
                    if(code != 1){
                        return proxy.$msg.error(msg);
                    }else{
                        let files = [];
                        if(data.files){
                            let array = data.files;
                            for (let index = 0; index < array.length; index++) {
                                let obj = {
                                    name: array[index].name,
                                    url: array[index].xkey,
                                }
                                files.push(obj);
                            }
                        }
                        data.files = files;
                        data.entrust_stage = data.entrust_stage.split(',');
                        data.lawyer_id = data.lawyer_id.split(',').map(Number);
                        state.editData = {
                            ...state.editData,
                            title: '编辑案件',
                            model: data
                        }
                        proxy.$refs.dialogEdit.openDialog();
                    }
                })
            }

            //编辑案件
            const handleEdit = (e) => {
                //格式化附件
                let array = e.files;
                let files = [];
                if(e.files){
                    for (let index = 0; index < array.length; index++) {
                        if(array[index].id){
                            files.push(array[index].xkey)
                        }else{
                            files.push(array[index].url);
                        }
                    }
                }                
                proxy.$http.post('/oa/Lawcase/caseForm',{
                    id: router.currentRoute.value.query.id,
                    name: e.name,
                    priority: e.priority,
                    case_type: e.case_type,
                    business_type: e.business_type,
                    status: e.status,
                    case_no: e.case_no,
                    area: e.area,
                    entrust_stage: String(e.entrust_stage),
                    target_amount: e.target_amount,
                    contract_amount: e.contract_amount,
                    lawyer_id: String(e.lawyer_id),
                    evidence: e.evidence,
                    description: e.description,
                    files: String(files),
                })
                .then(res=> {
                    const { code, msg ,data } = res;
                    if(code != 1){
                        return proxy.$msg.error(msg);
                    }else{
                        proxy.$msg.success('提交成功');
                        getDetail();
                    }
                })
            }

            //打开添加跟进
            const handleFollow = () => {
                state.opDialog = true;
                state.staticData.lawcase_id = router.currentRoute.value.query.id;
                state.staticData.lawcase_status = state.detailData.status;
            }

            //打开开庭信息
            const handleSession = () => {
                state.courtDialog = true;
                state.courtData.lawcase_id = router.currentRoute.value.query.id;
            }

            //打开添加判决
            const handleJudgment = () => {
                state.judgmentData.lawcase_id = router.currentRoute.value.query.id;
                state.judgmentData.lawcase_status = state.detailData.status;
                state.judgmentDialog = true;
            }

            //打开保全信息
            const handleAddPre = () => {
                proxy.$refs.dialogPre.openDialog();
            }

            //提交保全信息
            const handlePre = (e) => {
                e.lawcase_id = router.currentRoute.value.query.id;
                proxy.$http.post('/oa/Lawcase/preservationForm', e)
                .then(res=> {
                    const { code, msg ,data } = res;
                    if(code != 1){
                        return proxy.$msg.error(msg);
                    }else{
                        proxy.$msg.success('提交成功');
                        window.location.reload();
                    }
                })
            }

            //打开结案/归档
            const handleAddFinish = (type) => {
                state.finishType = type;
                if(type == 1){
                    //结案
                    state.finishData = {
                        ...state.finishData,
                        title: '结案',
                        data: [
                            {formType: 'select', label: '结案状态', prop: 'status', data:[{value: 3, label: '已结案'}, {value: 4, label: '终本结案'}], rules: [{ required: true, message: '请选择结案状态', trigger: 'blur' }], selectlabel: 'label', selectvalue: 'value', placeholder: '请选择'},
                        ]
                    }                    
                }else{
                    //归档
                    state.finishData = {
                        ...state.finishData,
                        title: '归档',
                        data: [
                            {formType: 'select', label: '归档状态', prop: 'status', data:[{value: 1, label: '未归档'}, {value: 2, label: '已归档'}], rules: [{ required: true, message: '请选择归档状态', trigger: 'blur' }], selectlabel: 'label', selectvalue: 'value', placeholder: '请选择'},
                            {formType: 'input', label: '归档编号', prop: 'number', rules: [{ required: true, message: '请输入归档编号', trigger: 'blur' }], placeholder: '请输入归档编号'},
                        ]
                    }
                }
                proxy.$refs.dialogFinish.openDialog();
            }

            //提交结案/归档
            const handleFinish = (e) => {
                proxy.$http.post('/oa/Lawcase/closeForm',{
                    lawcase_id: router.currentRoute.value.query.id,
                    type: state.finishType,
                    status: e.status,
                    number: e.number,
                })
                .then(res=> {
                    const { code, msg ,data } = res;
                    if(code != 1){
                        return proxy.$msg.error(msg);
                    }else{
                        proxy.$msg.success('提交成功');
                        window.location.reload();
                    }
                })
            }

            //获取客户列表
            const getCustomer = (page,perPage) => {
                state.loading = true;
                proxy.$http.get('/oa/Customer/index',{
                    page: page ? page : 1,
                    perPage: perPage ? perPage : 10,
                    name: state.SearchForm.name,
                })
                .then(res=> {
                    state.loading = false;
                    const { code, msg ,data } = res;
                    if(code != 1){
                        return proxy.$msg.error(msg);
                    }else{
                        state.count = data.count;
                        state.page = data.page;
                        state.perPage = data.perPage;
                        state.customerData = data.list;
                    }
                })
            }

            //选中客户
            const handleCurrent = (e) => {
                state.bindID = e.id;
            }

            //打开绑定/换绑/取消关联客户
            const handleOpBind = (type,item) => {
                state.bindType = type;
                if(type == 1){                    
                    if(state.detailData.key_id == 0){
                        state.bindTitle = '关联客户';
                    }else{
                        state.radio = item.key_id;
                        state.bindTitle = '更换客户';
                    }
                    state.bindDialog = true;
                }else{
                    proxy.$confirm("此操作会将该案件取消关联客户, 是否继续?", "提示", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                    })
                    .then(async () => {
                        handleBind();
                    })
                    .catch(() => {})
                }
            }

            //提交操作关联客户
            const handleBind = () => {
                let form = {};
                if(state.bindType == 1){
                    if(!state.bindID){
                        return proxy.$msg.error('请选择关联客户');
                    }
                    form = {
                        type: 1,
                        id: router.currentRoute.value.query.id,
                        key_id: state.bindID,
                    }
                }else{
                    form = {
                        type: 1,
                        id: router.currentRoute.value.query.id,
                        key_id: 0,
                    }
                }
                state.btnLoading = true;
                proxy.$http.post('/oa/Lawcase/caseBind', form)
                .then(res=> {
                    state.btnLoading = false;
                    let { code, msg, data } = res;
                    if(code != 1){
                        return proxy.$msg.error(msg);
                    }else{
                        state.bindDialog = false;
                        proxy.$msg.success('提交成功!');
                        getDetail();
                    }
                })
            }

            //取消操作关联客户
            const handleBindClose = () => {
                state.bindDialog = false;
            }

            //提交表单后,刷新页面
            const handleSubmit = () => {
                window.location.reload();
            }

            //清空
            const resetForm = (formName) => {
                proxy.$refs[formName].resetFields();
                getCustomer(state.page,state.perPage);
            }

            //Tabs
            const handleTab = () => {
                
            }

            //跳转客户详情
            const handlePath = () => {
                router.push({path: '/CustomerDetail', query: { id: state.detailData.key_id, case_id: state.detailData.id, path: '/CaseDetail', type: router.currentRoute.value.query.type}});
            }

            //返回上一页
            const handleBack = () => {
                router.push({path: router.currentRoute.value.query.pathUrl, query: {type: router.currentRoute.value.query.type}});
            }

            //格式化案件类型
            const formatType = (item) => {
                if(item){
                    return item.slice(0,1);
                }
            }

            //获取权限
            const authMenu = (value) => {
                let currentRouter = router.currentRoute.value.path;
                let menuArr = (proxy.$public.authMenu(currentRouter).split(','));
                for (let index = 0; index < menuArr.length; index++) {
                    if(value == menuArr[index]){
                        return true
                    }
                }
            }

            //分页
            const handleSizeChange = (val) => {
                state.perPage = val;
                getCustomer(state.page,state.perPage);
            }

            //页码
            const handleCurrentChange = (val) => {
                state.page = val;
                getCustomer(state.page,state.perPage);
            }
            
            //Dom加载
            onMounted(()=>{
                authMenu();
                getDetail();
                getCustomer();
            })
            
            return {
                ...toRefs(state),
                
                //请求方法
                getDetail,
                getCustomer,
                handleAddEdit,
                handleEdit,
                handleFollow,
                handleSession,
                handleJudgment,
                handleAddPre,
                handlePre,
                handleAddFinish,
                handleFinish,
                handleCurrent,
                handleOpBind,
                handleBind,
                handleBindClose,
                handleTab,
                handleSubmit,

                //组件方法
                authMenu,
                resetForm,
                handlePath,
                handleBack,
                formatType,
                handleSizeChange,
                handleCurrentChange,
            }

        },
    })
</script>

<style scoped>
    .fxn-detail{
        margin-right: 20px;
    }

    .fxn-detail-user{
        padding: 40px;
        background: #FFFFFF;
    }

    .fxn-detail-user .title{
        font-size: 24px;
        overflow: hidden;
    }

    .fxn-detail-user .title .icon{
        margin-right: 4px;
        width: 32px;
        height: 32px;
        color: #FFFFFF;
        font-size: 16px;
        text-align: center;
        line-height: 32px;
        border-radius: 50%;
        background: rgba(46, 60, 179, .9);
        display: inline-block;
    }

    .fxn-detail-user .status{
        margin: 20px 0;
        color: #999999;
        overflow: hidden;
    }

    .fxn-detail-user .status .item{
        margin-right: 20px;
        display: inline-block;
    }

    .fxn-detail-user .status .item span{
        color: rgba(46, 60, 179, .9);
    }

    .fxn-detail-user .button{
        overflow: hidden;
    }

    .fxn-detail-wrap{
        margin: 20px 0;
        padding: 40px;
        background: #FFFFFF;
    }

    .bind-page{
        margin-top: 20px;
    }
</style>